"""
分析师智能体
负责市场数据分析、行业研究和个股研究
"""
from typing import List, Dict, Any, Callable, Type, Optional, Union
from crewai import Agent
from loguru import logger
from pydantic import BaseModel, Field
import numpy as np
import akshare as ak

from agents.base_agent import BaseInvestmentAgent
from utils.stock_analysis import calculate_technical_indicators, analyze_financial_data, calculate_valuation_metrics
from database.data_collector import DataCollector

class MarketAnalyst(BaseInvestmentAgent):
    """市场分析师智能体"""
    
    def __init__(self, verbose: bool = False):
        """初始化市场分析师智能体"""
        from config.settings import AGENT_CONFIG
        name = AGENT_CONFIG["market_analyst"]["name"]
        role = AGENT_CONFIG["market_analyst"]["role"]
        goal = "分析市场整体趋势，评估宏观经济环境，识别市场机会与风险"
        backstory = f"""
        你是{name}，一位资深市场分析师，拥有15年金融市场分析经验和CFA资格认证。
        你擅长宏观经济分析和技术指标分析，曾准确预测多次重大市场转折点。
        你的分析风格注重数据和历史模式，同时关注政策和市场情绪因素。
        你致力于为投资团队提供全面、深入且客观的市场分析报告。
        """
        
        # 使用字典格式创建工具
        logger.debug("初始化市场分析师工具")
        tools = [
            {
                "name": "market_trend_analysis",
                "func": self._analyze_market_trend,
                "description": "分析大盘走势和市场趋势，评估市场情绪和技术指标"
            },
            {
                "name": "sector_rotation_analysis",
                "func": self._analyze_sector_rotation,
                "description": "分析行业板块轮动情况，识别热点行业和资金流向"
            },
            {
                "name": "economic_indicator_analysis",
                "func": self._analyze_economic_indicators,
                "description": "分析宏观经济指标，包括GDP、PMI、CPI等数据"
            }
        ]
        tools = [tool for tool in tools]
        super().__init__(name, role, goal, backstory, tools, verbose)
        logger.info(f"市场分析师 {name} 初始化完成")
    
    def _analyze_market_trend(self, timeframe: str = "daily") -> Dict[str, Any]:
        """
        分析市场整体趋势
        
        参数:
            timeframe: 时间周期，可选 daily/weekly/monthly
            
        返回:
            市场趋势分析结果，包含:
            - trend_direction: 趋势方向(上涨/下跌/盘整)
            - strength: 趋势强度(0-100)
            - key_support: 关键支撑位
            - key_resistance: 关键阻力位
            - volume_analysis: 成交量分析
            - sentiment: 市场情绪
        """
        logger.info(f"分析市场趋势，时间周期: {timeframe}")
        
        try:
            # 获取市场指数代码配置
            from config.settings import MARKET_INDEX_CODE
            market_index_code = MARKET_INDEX_CODE
            if market_index_code == "000001":
                logger.warning("未配置市场指数代码，使用默认值: 000001")
            else:
                logger.info(f"市场指数代码: {market_index_code}")
            
            # 获取指数数据
            data_collector = DataCollector()
            index_data = data_collector.get_index_data(market_index_code)
            
            if index_data.empty:
                logger.warning("无法获取指数数据")
                return {"error": "无法获取指数数据"}
            
            # 计算技术指标
            close_prices = index_data.set_index('date')['close'].astype(float)
            ma20 = close_prices.rolling(window=20).mean().iloc[-1]
            ma60 = close_prices.rolling(window=60).mean().iloc[-1]
            
            # 判断趋势方向
            if close_prices.iloc[-1] > ma20 > ma60:
                trend_direction = "上涨"
                strength = min(int((close_prices.iloc[-1] / ma20 - 1) * 100), 100)
            elif close_prices.iloc[-1] < ma20 < ma60:
                trend_direction = "下跌"
                strength = min(int((1 - close_prices.iloc[-1] / ma20) * 100), 100)
            else:
                trend_direction = "盘整"
                strength = 0
                
            # 计算支撑位和阻力位
            recent_low = close_prices.iloc[-20:].min()
            recent_high = close_prices.iloc[-20:].max()
            
            # 创建默认市场情绪数据
            sentiment = {
                'fear_greed': 50,
                'market_breadth': 50,
                'volatility': 20.0,
                'northbound': 0.0
            }
            
            return {
                "trend_direction": trend_direction,
                "strength": strength,
                "key_support": recent_low,
                "key_resistance": recent_high,
                "volume_analysis": "放量" if index_data['volume'].iloc[-1] > index_data['volume'].mean() else "缩量",
                "sentiment": sentiment
            }
            
        except Exception as e:
            logger.error(f"市场趋势分析失败: {e}")
            return {"error": str(e)}
    
    def _analyze_sector_rotation(self) -> Dict[str, Any]:
        """
        分析行业板块轮动
        
        返回:
            行业板块轮动分析结果，包含:
            - hot_sectors: 热门行业及涨幅
            - cooling_sectors: 冷却行业及跌幅
            - money_flow: 资金流向分析
            - rotation_stage: 轮动阶段(早期/中期/晚期)
        """
        logger.info("分析行业板块轮动")
        
        try:
            # 获取行业数据
            data_collector = DataCollector()
            stock_list = data_collector.get_stock_list()
            
            if stock_list.empty:
                logger.warning("无法获取股票列表")
                return {"error": "无法获取股票列表"}
            
            # 获取各行业平均涨跌幅
            industry_data = []
            for industry in stock_list['industry'].unique():
                industry_stocks = stock_list[stock_list['industry'] == industry]
                if len(industry_stocks) > 0:
                    changes = []
                    for code in industry_stocks['code']:
                        stock_data = data_collector.get_daily_data(code)
                        if not stock_data.empty and '涨跌幅' in stock_data.columns:
                            changes.append(stock_data['涨跌幅'].iloc[-1])
                    if changes:
                        avg_change = np.mean(changes)
                        industry_data.append({
                            "industry": industry,
                            "avg_change": avg_change,
                            "count": len(changes)
                        })
            
            # 按涨跌幅排序
            sorted_industries = sorted(industry_data, key=lambda x: x['avg_change'], reverse=True)
            
            # 获取热门和冷却行业
            hot_sectors = [{"industry": x['industry'], "change": x['avg_change']}
                          for x in sorted_industries[:3]]
            cooling_sectors = [{"industry": x['industry'], "change": x['avg_change']}
                             for x in sorted_industries[-3:]]
            
            # 分析资金流向
            money_flow = "流入成长股" if hot_sectors[0]['change'] > 0.05 else "流入价值股"
            
            # 判断轮动阶段
            if hot_sectors[0]['change'] > 0.08:
                rotation_stage = "中期"
            elif hot_sectors[0]['change'] > 0.12:
                rotation_stage = "晚期"
            else:
                rotation_stage = "早期"
                
            return {
                "hot_sectors": hot_sectors,
                "cooling_sectors": cooling_sectors,
                "money_flow": money_flow,
                "rotation_stage": rotation_stage
            }
            
        except Exception as e:
            logger.error(f"行业轮动分析失败: {e}")
            return {"error": str(e)}
    
    def _analyze_economic_indicators(self) -> Dict[str, Any]:
        """
        分析宏观经济指标
        
        返回:
            宏观经济指标分析结果，包含:
            - growth_indicators: 增长类指标 (GDP、工业增加值等)
            - inflation_indicators: 通胀类指标 (CPI、PPI等)
            - financial_indicators: 金融类指标 (M2、社融、利率等)
            - employment: 就业指标 (失业率等)
            - composite_assessment: 综合评估 (经济周期、风险预警等)
        """
        logger.info("分析宏观经济指标")
        
        try:
            from config.settings import MACRO_DATA_SOURCE
            import akshare as ak
            
            # 初始化默认值
            indicators = {
                "growth_indicators": {},
                "inflation_indicators": {},
                "financial_indicators": {},
                "employment": {},
                "composite_assessment": {}
            }

            # 1. 获取增长类指标（使用最新接口）
            try:
                # GDP数据（季度）
                gdp_data = ak.macro_china_gdp()
                indicators['growth_indicators']['gdp'] = {
                    'current': gdp_data.iloc[-1]['国内生产总值'],
                    'prev': gdp_data.iloc[-2]['国内生产总值'],
                    'yoy_growth': gdp_data.iloc[-1]['同比增长']
                }
                
                # 工业增加值（使用制造业PMI替代）
                pmi_data = ak.macro_china_pmi()
                indicators['growth_indicators']['manufacturing_pmi'] = {
                    'current': pmi_data.iloc[-1]['制造业PMI'],
                    'trend': pmi_data.iloc[-3:]['制造业PMI'].mean()
                }
            except Exception as e:
                logger.error(f"增长指标获取失败: {e}")

            # 2. 获取通胀类指标（使用简化接口）
            try:
                # 分别获取CPI和PPI数据
                cpi_data = ak.macro_china_cpi()
                ppi_data = ak.macro_china_ppi()
                indicators['inflation_indicators'] = {
                    'cpi': cpi_data.iloc[-1]['全国'],
                    'ppi': ppi_data.iloc[-1]['当月']
                }
            except Exception as e:
                logger.error(f"通胀指标获取失败: {e}")

            # 3. 获取金融类指标（使用银行间同业拆借利率）
            try:
                # 货币供应量
                money_supply = ak.macro_china_money_supply()
                indicators['financial_indicators'] = {
                    'm2_growth': money_supply.iloc[-1]['M2同比增长'],
                    'social_financing': money_supply.iloc[-1]['社会融资规模增量'],
                    'shibor': ak.rate_interbank().iloc[-1]['隔夜']
                }
            except Exception as e:
                logger.error(f"金融指标获取失败: {e}")

            # 4. 就业指标（待完善实际数据接口）
            # 由于AKShare接口变动，当前接口不可用，暂使用注释标记待完善
            indicators['employment'] = {
                # 'unemployment_rate': 实际数据获取逻辑,
                # 'historical_trend': 实际数据获取逻辑
            }

            # 5. 综合评估（简化模型）
            try:
                # 经济周期判断
                pmi = indicators['growth_indicators'].get('manufacturing_pmi', {}).get('current', 50)
                cpi = indicators['inflation_indicators'].get('cpi', 2.5)
                
                economic_cycle = "扩张期" if pmi > 50 and cpi < 3.5 else "收缩期"
                
                # 风险预警
                warnings = []
                if indicators['financial_indicators'].get('m2_growth', 0) > 12:
                    warnings.append("货币供应增长过快")
                if indicators['employment'].get('unemployment_rate', 0) > 5.5:
                    warnings.append("失业率超过警戒线")
                
                indicators['composite_assessment'] = {
                    'economic_cycle': economic_cycle,
                    'risk_warnings': warnings or None,
                    'composite_index': (pmi * 0.6 + (100 - cpi*10) * 0.4)  # 简化计算公式
                }
            except Exception as e:
                logger.error(f"综合评估失败: {e}")

            return indicators
            
        except Exception as e:
            logger.error(f"宏观经济指标分析失败: {e}")
            return {"error": str(e)}

    def _calculate_composite_index(self, indicators: dict) -> float:
        """计算宏观经济综合指数"""
        weights = {
            'gdp': 0.3,
            'industrial_output': 0.2,
            'cpi': 0.15,
            'ppi': 0.15,
            'm2': 0.1,
            'unemployment': 0.1
        }
        
        score = 0
        try:
            # GDP评分
            gdp_growth = indicators['growth_indicators']['gdp']['yoy_growth']
            score += min(max((gdp_growth - 5.5) / 2.5, 0), 1) * weights['gdp']
            
            # 工业增加值评分
            industrial_growth = indicators['growth_indicators']['industrial_output']['current']
            score += min(max((industrial_growth - 5) / 5, 0), 1) * weights['industrial_output']
            
            # CPI评分（维持2%-3%为最佳）
            cpi = indicators['inflation_indicators']['cpi']['current']
            score += (1 - abs(cpi - 2.5)/1.5) * weights['cpi']
            
            # PPI评分
            ppi = indicators['inflation_indicators']['ppi']['current']
            score += (1 - abs(ppi)/10) * weights['ppi']
            
            # M2评分（10%-12%为理想区间）
            m2_growth = indicators['financial_indicators']['m2']
            score += min(max((12 - abs(m2_growth - 11)) / 2, 0), 1) * weights['m2']
            
            # 失业率评分
            unemployment = indicators['employment']['urban_unemployment']
            score += (1 - (unemployment - 4.5)/3) * weights['unemployment']
            
            return round(score * 100, 1)
        except Exception as e:
            logger.error(f"综合指数计算失败: {e}")
            return 0.0


class StockAnalyst(BaseInvestmentAgent):
    """个股分析师智能体"""
    
    def __init__(self, verbose: bool = False):
        """初始化个股分析师智能体"""
        
        name = "李芳华"
        role = "高级个股分析师"
        goal = "深入研究个股基本面和技术面，发掘具有投资价值的标的"
        backstory = """
        你是李芳华，一位专注于A股市场个股研究的分析师，拥有10年从业经验。
        你擅长财务报表分析和公司治理评估，对上市公司的商业模式有深刻理解。
        你曾经成功发掘多只10倍股，包括新兴科技和传统行业转型的优质企业。
        你的研究方法注重基本面与市场预期的匹配度，善于识别被市场低估的价值。
        """
        
        # 使用字典格式创建工具
        tools = [
            {
                "name": "stock_fundamental_analysis",
                "func": self._analyze_stock_fundamentals,
                "description": "分析个股基本面，包括财务报表、经营状况和成长性"
            },
            {
                "name": "stock_technical_analysis",
                "func": self._analyze_stock_technicals,
                "description": "分析个股技术指标，包括价格趋势、交易量和技术形态"
            },
            {
                "name": "stock_valuation",
                "func": self._valuate_stock,
                "description": "对个股进行估值，计算PE、PB、PS等估值指标"
            }
        ]
        
        # 添加详细工具调试日志
        logger.debug(f"个股分析师工具列表: {tools}")
        
        super().__init__(name, role, goal, backstory, tools, verbose)
        logger.info(f"个股分析师 {name} 初始化完成")
    
    def _analyze_stock_fundamentals(self, stock_code: str) -> Dict[str, Any]:
        """
        分析个股基本面
        
        参数:
            stock_code: 股票代码
            
        返回:
            个股基本面分析结果，包含:
            - revenue_growth: 收入增长率
            - profit_growth: 利润增长率
            - roe: 净资产收益率
            - financial_health: 财务健康状况
            - competitive_advantage: 竞争优势评估
        """
        logger.info(f"分析股票 {stock_code} 基本面")
        try:
            # 获取财务数据
            financials = analyze_financial_data(stock_code)
            
            if "error" in financials:
                raise ValueError(financials["error"])
                
            return {
                "revenue_growth": financials["growth"]["revenue_growth"],
                "profit_growth": financials["growth"]["profit_growth"],
                "roe": financials["profitability"]["roe"],
                "financial_health": {
                    "debt_ratio": financials["solvency"]["debt_to_equity"],
                    "current_ratio": financials["solvency"]["current_ratio"]
                },
                "competitive_advantage": {
                    "gross_margin": financials["profitability"]["gross_margin"],
                    "operating_margin": financials["profitability"]["operating_margin"]
                }
            }
            
        except Exception as e:
            logger.error(f"分析个股基本面失败: {e}")
            return {
                "revenue_growth": None,
                "profit_growth": None,
                "roe": None,
                "financial_health": {
                    "debt_ratio": None,
                    "current_ratio": None
                },
                "competitive_advantage": {
                    "gross_margin": None,
                    "operating_margin": None
                }
            }
    
    def _analyze_stock_technicals(self, stock_code: str) -> Dict[str, Any]:
        """
        分析个股技术指标
        
        参数:
            stock_code: 股票代码
            
        返回:
            个股技术指标分析结果
        """
        logger.info(f"分析股票 {stock_code} 技术指标")
        # 调用技术指标计算函数
        return calculate_technical_indicators(stock_code)
    
    def _valuate_stock(self, stock_code: str) -> Dict[str, Optional[float]]:
        """
        对个股进行估值
        
        参数:
            stock_code: 股票代码
            
        返回:
            个股估值结果，包含:
            - pe: 市盈率
            - pb: 市净率
            - ps: 市销率
            - fair_value: 公允价值
            - upside_potential: 上涨潜力
        """
        logger.info(f"对股票 {stock_code} 进行估值")
        try:
            # 获取估值指标
            valuation = calculate_valuation_metrics(stock_code)
            
            if "error" in valuation:
                raise ValueError(valuation["error"])
                
            return {
                "pe": valuation["pe_ttm"],
                "pb": valuation["pb"],
                "ps": valuation["ps_ttm"],
                "fair_value": valuation["fair_value"],
                "upside_potential": valuation["upside_potential"]
            }
            
        except Exception as e:
            logger.error(f"个股估值失败: {e}")
            return {
                "pe": None,
                "pb": None,
                "ps": None,
                "fair_value": None,
                "upside_potential": None
            }